package com.yzs.utils;

import com.yzs.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Component
public class EmailUtil {

    @Autowired
    JavaMailSender javaMailSender;
    @Autowired
    RedisService redisService;

    public String sendEmailVerifyCode(String code, String from, String to) {
        try {
            Object o = redisService.get("VerifyCode_" + to);
            if (Objects.isNull(o)) {
                // 用来设置邮件信息
                SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
                // 设置邮件标题
                simpleMailMessage.setSubject("验证码，请勿告诉他人");
                // 设置邮件内容
                simpleMailMessage.setText("您收到的验证码是：" + code);
                // 设置源邮箱
                simpleMailMessage.setFrom(from);
                // 设置目的邮箱
                simpleMailMessage.setTo(to);
                // 发送
                javaMailSender.send(simpleMailMessage);
                // 没有出现异常，正常发送，保存到redis中，返回true
                redisService.set("VerifyCode_" + to, code, 60);
            } else {
                return "验证码已经发送过了，请稍后再试！";
            }
            return "验证码发送成功！";
        } catch (MailException e) {
            // 发送过程中，发生错误，打印错误信息，返回false
            e.printStackTrace();
            return "验证码发送是失败，请重试！";
        }
    }

}
